# coding: utf-8

import os
import uuid
from flask import Blueprint, render_template, request, session
from app.utils import helper

code = Blueprint('code', __name__)


@code.route('/upload/code_upload/', methods=['GET', 'POST'])
def upload():
    """
    上传文件
        步骤：
            1. 检查上传文件后缀名
            2. 接收用户上传文件,并写入到服务器本地. 从file_obj.stream中读取内容，写入到文件
    """
    if request.method == "GET":
        return render_template('upload/code_upload.html')
    file_obj = request.files.get('code')

    # 步骤1
    name_ext = file_obj.filename.rsplit('.', maxsplit=1)
    if len(name_ext) != 2:
        return "请上传zip压缩文件"
    if name_ext[1] != 'zip':
        return "请上传zip压缩文件"

    # 步骤2
    # file_path = os.path.join("zips", file_obj.filename)
    # file_obj.save(file_path)

    target_path = os.path.join('files', str(uuid.uuid4()))
    file_name = file_obj.filename.split('.')[0]
    helper.insert("insert into files_upload(file_name,target_path,user_id)values(%s,%s,%s)",
                  (file_name, target_path, session['user_info']['id']))

    return "上传成功"
